package com.bawei.module_main

import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_base.RoutePath
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.mvi.BaseMviActivity
import com.bawei.module_main.apter.MainPageAdapter
import com.bawei.module_main.databinding.ActivityMainAactivityBinding
import com.bawei.module_main.tab.NormalTabView
import com.bawei.module_main.tab.RoundTabView
import dagger.hilt.android.AndroidEntryPoint
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener
import okhttp3.internal.http2.Settings
import java.util.jar.Manifest

@AndroidEntryPoint
@Route(path = RoutePath.PATH_MAIN_PAGE)
class MainAActivity : BaseActivity<ActivityMainAactivityBinding>() {

    private lateinit var mNavController: NavigationController
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPagerAdapter: MainPageAdapter

    private var needUserPermissions= arrayListOf(
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.READ_EXTERNAL_STORAGE
        , android.Manifest.permission.ACCESS_FINE_LOCATION
    )
    private val unGrantPermissions= arrayListOf<String>()
    private var hasUnGranted:Boolean=false

    override fun getLayoutId(): Int {
        return R.layout.activity_main_aactivity
    }


    override fun initViews() {
        //底部导航
        mNavController = mDataNBinding.mainBottomNav.custom()
            .addItem(newNormalTabItem(R.drawable.nav_home_normal, R.drawable.nav_home_checked, "首页"))
            .addItem(newNormalTabItem(R.drawable.nav_movie_normal, R.drawable.nav_movie_checked, "放映厅"))
            .addItem(newRoundTabItem(R.drawable.nav_add_normal, R.drawable.nav_add_checked, "发布"))
            .addItem(newNormalTabItem(R.drawable.nav_live_normal, R.drawable.nav_live_checked, "直播"))
            .addItem(newNormalTabItem(R.drawable.nav_mine_normal, R.drawable.nav_mine_checked, "我的"))
            .build()

        //使用ARouter路由获取页面
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_HOMEPLAY).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_LIVE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MINE).navigation() as Fragment)


        mPagerAdapter = MainPageAdapter(supportFragmentManager, fragments, FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT)
        mDataNBinding.mainViewPager.apply {
            adapter = mPagerAdapter
            offscreenPageLimit = 3
        }

        mNavController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
            override fun onSelected(index: Int, old: Int) {
                when(index){
                    0,1-> {
                        mDataNBinding.mainViewPager.currentItem = index
                    }
                    2 -> {
                        ARouter.getInstance().build(RoutePath.PATH_PUBLISH_PAGE).navigation()
                        mNavController.setSelect(old) //恢复之前样式
                    }
                    3,4 -> {
                        mDataNBinding.mainViewPager.currentItem = index - 1
                    }
                }
            }

            //监听重复事件,避免快速跳转
            override fun onRepeat(index: Int) {
                if (index == 2){
                    ARouter.getInstance().build(RoutePath.PATH_PUBLISH_PAGE).navigation()
                }
            }
        })

        mDataNBinding.mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                when(position){
                    0,1 -> mNavController.setSelect(position)
                    2,3 -> mNavController.setSelect(position + 1)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })
        //延迟发起用户授权
        mDataNBinding.mainViewPager.postDelayed({
            autoRequestPermissions()
        },2000)

    }

    private fun autoRequestPermissions():Boolean {
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
            //清理
            unGrantPermissions.clear()
            //发起授权
            needUserPermissions.forEach {
                var state=checkSelfPermission(it)
                if(state==PackageManager.PERMISSION_DENIED){
                   unGrantPermissions.add(it)
                }
            }
            //发起用户授权的请求
            if(unGrantPermissions.size>0){
                requestPermissions(unGrantPermissions.toTypedArray(),100)
                return false
            }
        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode==100&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            //检查未授权的权限是否被同意
            unGrantPermissions.forEach{
                if(checkSelfPermission(it)==PackageManager.PERMISSION_DENIED){
                    hasUnGranted=true
                }
            }
        }
        if(hasUnGranted){
            AlertDialog.Builder(this@MainAActivity).apply{
                setTitle("权限提示")
                setMessage("您没有授权，请到设置中心开启权限！！")
                setPositiveButton("去设置"){dialog,_->{
                    dialog.dismiss()
                    hasUnGranted=false
                    jumToAppDetail()
                }
                    setNegativeButton("取消"){dialog,_->{
                        dialog.dismiss()
                        hasUnGranted=false
                    }
                    }

                }
            }
        }
    }

    /**
     * 跳转到应用设置中心
     */
    private fun jumToAppDetail(){
        this@MainAActivity.startActivity(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data= Uri.fromParts("package",packageName,null)
        })
    }

    private fun newNormalTabItem(defaultIcon: Int, checkedIcon: Int, title: String): BaseTabItem {
        return NormalTabView(this@MainAActivity).apply {
            initData(defaultIcon, checkedIcon, title)
            setDefaultTextColor(R.color.main_bottom_default_color)
            setCheckedTextColor(R.color.main_bottom_check_color)
        }
    }

    private fun newRoundTabItem(defaultIcon: Int, checkedIcon: Int, title: String): BaseTabItem{
        return RoundTabView(this@MainAActivity).apply {
            initData(defaultIcon, checkedIcon, title)
            setDefaultTextColor(R.color.main_bottom_default_color)
            setCheckedTextColor(R.color.main_bottom_check_color)
        }
    }

}